<?php
!function_exists('readover') && exit('Forbidden');
@include_once(D_P.'data/bbscache/cn_config.php');
if (!$action) {	
	require_once(R_P.'require/credit.php');
	$credittype = GetCreditType();
	ifcheck($cn_open,'open');
	ifcheck($cn_remove,'remove');
	ifcheck($cn_newcolony,'newcolony');
	ifcheck($cn_virement,'virement');
	
	$creategroup = ''; $num = 0;
	foreach ($ltitle as $key => $value) {
		if ($key!=1 && $key!=2) {
			$num++;
			$htm_tr = $num % 4 == 0 ? '</tr><tr>' : '';
			$g_checked = strpos($cn_groups,",$key,")!==false ? 'checked' : '';
			$creategroup .= "<td><input type=\"checkbox\" name=\"groups[]\" value=\"$key\" $g_checked>$value</td>$htm_tr";
		}
	}
	$creategroup && $creategroup = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\" align=\"center\"><tr>$creategroup</tr></table>";
	
	require_once PrintHack('admin');
} elseif ($action=='setting') {
	@include_once(D_P.'data/bbscache/cn_config.php');
	!is_array($config = $_POST['config']) && $config = array();
	foreach ($config as $key => $value) {
		if ($value) {
			$isint = false;
			if ($_POST['step']=='basic') {
				if ($key=='name' || $key=='moneytype') {
					$config[$key] = Char_cv($value);
				} elseif ($key=='rate') {
					$config[$key] = (double)$value;
				} else {
					$isint = true;
				}
			} else {
				$isint = true;
			}
			$isint && $config[$key] = (int)$value;
		}
	}
	if ($_POST['step']=='basic') {
		!is_array($groups = $_POST['groups']) && $groups = array();
		$config['groups'] = ','.implode(',',$groups).',';
	}
	$updatecache = false;
	foreach ($config as $key => $value) {
		if (${'cn_'.$key}!=$value) {
			$db->pw_update(
				"SELECT hk_name FROM pw_hack WHERE hk_name='cn_$key'",
				"UPDATE pw_hack SET hk_value='$value' WHERE hk_name='cn_$key'",
				"INSERT INTO pw_hack(hk_name,hk_value) VALUES ('cn_$key','$value')"
			);
			$updatecache = true;
		}
	}
	$j_url = '';
	if ($_POST['step']=='updatecache') {
		$updatecache = true;
		$j_url = "$basename&action=cache";
	} elseif ($_POST['step']=='photo') {
		$j_url = "$basename&action=photo";
	}
	$updatecache && updatecache_cy();
	adminmsg('operate_success',$j_url);
} elseif ($action=='photo') {
	@include_once(D_P.'data/bbscache/cn_config.php');
	require_once(R_P.'require/credit.php');
	list($credittype,$creditunit) = GetCreditValue($cn_moneytype);
	
	!in_array($cn_mkdir,array(1,2,3)) && $cn_mkdir = 1;
	${'mkdir'.$cn_mkdir} = 'checked';
	
	ifcheck($cn_phopen,'phopen');
	require_once PrintHack('admin');
} elseif ($action=='class') {
	@include_once(D_P.'data/bbscache/cn_config.php');
	$cnclassdb = array();
	$query = $db->query('SELECT * FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$rt['cnsum'] = (int)$rt['cnsum'];
		$cnclassdb[] = $rt;
	}
	$db->free_result($query);
	require_once PrintHack('admin');
} elseif ($action=='update_cl') {
	$updatecache = false;
	$j_url = "$basename&action=class";
	$step = Char_cv(GetGP('step'));
	if ($step=='add') {
		!is_array($cname = $_POST['cname']) && $cname = array();
		$insert = $cnames = '';
		foreach ($cname as  $key => $value) {
			if (is_numeric($key)) {
				$value = Char_cv(trim($value));
				if ($value) {
					$cnames .= ",'$value'";
					$insert .= ",('$value')";
				}
			}
		}
		if ($cnames) {
			$query = $db->query("SELECT cname FROM pw_cnclass WHERE cname IN (".substr($cnames,1).")");
			while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
				$rt[0] = addslashes($rt[0]);
				$insert = str_replace(",('$rt[0]')",'',$insert);
			}
		}
		if ($insert) {
			$updatecache = true;
			$db->update('INSERT INTO pw_cnclass (cname) VALUES '.substr($insert,1));
		}
	} elseif ($step=='edit') {
		!is_array($selid = $_POST['selid']) && $selid = array();
		foreach ($selid as  $key => $value) {
			if (is_numeric($key)) {
				$value = Char_cv(trim($value));
				if ($value && !$db->get_value("SELECT cid FROM pw_cnclass WHERE cname='$value' AND cid!='$key'")) {
					$updatecache = true;
					$db->update("UPDATE pw_cnclass SET cname='$value' WHERE cid='$key'");
				}
			}
		}
	} elseif ($step=='del') {
		$id = (int)$_GET['id'];
		if ($id) {
			$updatecache = true;
			$db->update("UPDATE pw_colonys SET classid='' WHERE classid='$id'");
			$db->update("DELETE FROM pw_cnclass WHERE cid='$id'");
		}
	} elseif ($step=='updatecache') {
		$db->update("UPDATE pw_cnclass SET cnsum='0'");
		$query = $db->query("SELECT id,classid,COUNT(*) FROM pw_colonys WHERE classid>0 GROUP BY classid");
		while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
			if (!$db->get_value("SELECT COUNT(*) FROM pw_cnclass WHERE cid='$rt[1]'")) {
				$db->update("UPDATE pw_colonys SET classid='0' WHERE id='$rt[0]'");
			} else {
				$db->update("UPDATE pw_cnclass SET cnsum='$rt[2]' WHERE cid='$rt[1]'");
			}
		}
		$updatecache = true;
		$j_url = "$basename&action=cache";
	}
	$updatecache && updatecache_cnc();
	adminmsg('operate_success',$j_url);
} elseif ($action=='colony') {
	@include_once(D_P.'data/bbscache/cn_config.php');
	@include_once(D_P.'data/bbscache/cn_class.php');
	!is_array($cnclassdb) && $cnclassdb = array();
	$pages = '';
	$db_perpage = 20;
	$colonys = array();
	$page = GetGP('page');
	(int)$page<1 && $page = 1;
	$id = ($page-1)*$db_perpage;
	$query = $db->query("SELECT id,cname,classid FROM pw_colonys LIMIT $id,$db_perpage");
	while ($rt = $db->fetch_array($query)) {
		$rt['cname'] = trim($rt['cname']);
		$rt['classname'] = $rt['classid'] ? $cnclassdb[$rt['classid']] : '';
		$colonys[] = $rt;
	}
	$db->free_result($query);
	$count = $db->get_value('SELECT COUNT(*) FROM pw_colonys');
	if ($count > $db_perpage) {
		require_once(R_P.'require/forum.php');
		$pages = numofpage($count,$page,ceil($count/$db_perpage),"$basename&action=colony&");
	}
	require_once PrintHack('admin');
} elseif ($action=='update_c') {
	$step = Char_cv(GetGP('step'));
	if ($step=='edit') {
		!is_array($cid = $_POST['cid']) && $cid = array();
		!is_array($cname = $_POST['cname']) && $cname = array();
		$sleep = 0;
		foreach ($cname as  $key => $value) {
			$value = Char_cv(trim($value));
			if (is_numeric($key) && $value && !$db->get_value("SELECT COUNT(*) FROM pw_colonys WHERE cname='$value' AND id!='$key'")) {
				$newcid = (int)$cid[$key];
				$oldcid = $db->get_value("SELECT classid FROM pw_colonys WHERE id='$key'");
				if ($newcid!=$oldcid) {
					$sleep%20==0 && sleep(1);
					$sleep++;
					$db->update("UPDATE pw_cnclass SET cnsum=cnsum-1 WHERE cid='$oldcid'");
					$db->update("UPDATE pw_cnclass SET cnsum=cnsum+1 WHERE cid='$newcid'");
				}
				$db->update("UPDATE pw_colonys SET cname='$value',classid='$newcid' WHERE id='$key'");
			}
		}
	} elseif ($step=='del') {
		$id = (int)$_GET['id'];
		$rt = $db->get_one("SELECT classid,cnimg FROM pw_colonys WHERE id='$id'");
		if (!empty($rt)) {
			$ftp = null;
			if ($db_ifftp) {
				require_once(R_P.'require/ftp.php');
				$ftp = new FTP($ftp_server,$ftp_port,$ftp_user,$ftp_pass,$ftp_dir);
			}
			Delcnimg($rt['cnimg']);
			$db->update("DELETE FROM pw_argument WHERE gid='$id'");
			$db->update("DELETE FROM pw_cmembers WHERE colonyid='$id'");
			$db->update("DELETE FROM pw_colonys  WHERE id='$id'");
			$db->update("UPDATE pw_cnclass SET cnsum=cnsum-1 WHERE cid='$rt[classid]'");
			if ($ftp) {
				$ftp->close(); unset($ftp);
			}
		}
	}
	updatecache_cnc();
	adminmsg('operate_success',"$basename&action=colony");
} elseif ($action=='log') {
	if ($_POST['step']!='del') {
		@include_once(D_P.'data/bbscache/cn_config.php');
		require_once GetLang('log');
		InitGP(array('keyword','page'));
		$db_perpage = 20;
		$logdb = array();
		$pages = $sqladd = $addpages = '';
		if ($keyword) {
			$sqladd = " AND descrip LIKE '%$keyword%'";
			$addpages = "&keyword=".rawurlencode($keyword);
		}
		(int)$page<1 && $page = 1;
		$id = ($page-1)*$db_perpage;
		$query = $db->query("SELECT id,type,field2,field3,username1,timestamp,descrip FROM pw_forumlog WHERE type LIKE 'cy\_%'$sqladd LIMIT $id,$db_perpage");
		while ($rt = $db->fetch_array($query)) {
			$rt['timestamp'] = get_date($rt['timestamp']);
			$rt['descrip'] = str_replace(array('[b]','[/b]'),array('<b>','</b>'),$rt['descrip']);
			$logdb[] = $rt;
		}
		$db->free_result($query);
		$count = $db->get_value("SELECT COUNT(*) FROM pw_forumlog WHERE type LIKE 'cy\_%'$sqladd");
		if ($count > $db_perpage) {
			require_once(R_P.'require/forum.php');
			$pages = numofpage($count,$page,ceil($count/$db_perpage),"$basename&action=log$addpages&");
		}
		require_once PrintHack('admin');
	} else {
		if (!($selid = checkselid(GetGP('selid','P')))) {
			$basename = 'javascript:history.go(-1);';
			adminmsg('operate_error');
		}
		$db->update("DELETE FROM pw_forumlog WHERE type LIKE 'cy\_%' AND id IN($selid)");
		adminmsg('operate_success',"$basename&action=log");
	}
} elseif ($action=='cache') {
	if ($_POST['step']=='delcolony') {
		$ftp = null;
		if ($db_ifftp) {
			require_once(R_P.'require/ftp.php');
			$ftp = new FTP($ftp_server,$ftp_port,$ftp_user,$ftp_pass,$ftp_dir);
		}
		$query = $db->query("SELECT id,cnimg FROM pw_colonys WHERE classid<1");
		while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
			Delcnimg($rt[1]);
			$db->update("DELETE FROM pw_argument WHERE gid='$rt[0]'");
			$db->update("DELETE FROM pw_cmembers WHERE colonyid='$rt[0]'");
			$db->update("DELETE FROM pw_colonys  WHERE id='$rt[0]'");
		}
		if ($ftp) {
			$ftp->close(); unset($ftp);
		}
		adminmsg('operate_success',"$basename&action=cache");
	} else {
		@include_once(D_P.'data/bbscache/cn_config.php');
		require_once PrintHack('admin');
	}
} elseif ($action=='argument'){
	InitGP(array(step));
	if($step == 'list'){
		InitGP(array('page','cid','author','ckauthor','keyword','ktype','ttype','ckkeyword','postdate1','postdate2','topped','orderby','sc','perpage'));
		if((int)$cid > 0){
			$sql .= ($sql ? " AND" : "")." c.classid='$cid'";
			$addpage .= "cid=$cid&";
		}
		
		if((int)$ttype > 0){
			if($ttype == 1){
				$sql .= ($sql ? " AND" : "")." a.tpcid='0'";
			}elseif($ttype == 2){
				$sql .= ($sql ? " AND" : "")." a.tpcid>'0'";
			}
		}
		
		if(strlen($author) > 0){
			if($ckauthor){
				$sql .= ($sql ? " AND" : "")." a.author='$author'";
				$addpage .="author=$author&ckauthor=$ckauthor&";
			}else{
				$sql .= ($sql ? " AND" : "")." a.author LIKE '%".str_replace('*','%',$author)."%'";
				$addpage .="author=$author&";
			}
		}
		if(strlen($keyword) > 0){
			if($ktype == 'subject'){
				if($ckkeyword){
					$sql .= ($sql ? " AND" : "")." a.subject='$keyword'";
					$addpage .="subject=$keyword&ckkeyword=$ckkeyword&";
				}else{
					$sql .= ($sql ? " AND" : "")." a.subject LIKE '%".str_replace('*','%',$keyword)."%'";
					$addpage .="subject=$keyword&";
				}
			}elseif($ktype == 'content'){
				if($ckkeyword){
					$sql .= ($sql ? " AND" : "")." a.content='$keyword'";
					$addpage .="content=$keyword&ckkeyword=$ckkeyword&";
				}else{
					$sql .= ($sql ? " AND" : "")." a.content LIKE '%".str_replace('*','%',$keyword)."%'";
					$addpage .="content=$keyword&";
				}
			}	
		}
		
		if (strlen($postdate1) > 0 || strlen($postdate2) > 0) {
			if ($postdate1) {
				!is_numeric($postdate1) && $postdate1 = PwStrtoTime($postdate1);
				$sql .= ($sql ? ' AND' : '')." a.postdate>'$postdate1'";
				$addpage .= "postdate1=$postdate1&";
			}
			if ($postdate2) {
				!is_numeric($postdate2) && $postdate2 = PwStrtoTime($postdate2);
				$sql .= ($sql ? ' AND' : '')." a.postdate<'$postdate2'";
				$addpage .= "postdate2=$postdate2&";
			}
		}
		
		if ($topped > 0){
			$sql .= ($sql ? " AND" : "")." a.topped='$topped'";
			$addpage .= "topped=$topped&";
		}
		$where = $sql ? "WHERE ".$sql : "";
		$orderby = $orderby == 'postdate' ? 'ORDER BY a.postdate' : 'ORDER BY a.authorid';
		$sc != 'ASC' && $sc = 'DESC';
		!$perpage && $perpage = $db_perpage;
		(int)$page<1 && $page = 1;
		$limit = " LIMIT ".($page-1)*$perpage.",".$perpage;
		$query = $db->query("SELECT a.tid,a.tpcid,a.gid,a.author,a.authorid,a.postdate,a.topped,a.subject,c.cname FROM pw_argument a LEFT JOIN pw_colonys c ON a.gid=c.id $where $orderby $sc $limit");
		while($rt = $db->fetch_array($query)){
			$rt['postdate'] = get_date($rt['postdate'],'Y-m-d');
			$rt['baktid'] = $rt['tid'];
			$rt['tpcid'] != 0 && $rt['baktid'] = $rt['tpcid'];
			$argumentdb[] = $rt;
		}
		$db->free_result($query);
		@extract($db->get_one("SELECT COUNT(*) AS count FROM pw_argument a LEFT JOIN pw_colonys c ON a.gid=c.id $where"));
		if ($count > $perpage) {
		require_once(R_P.'require/forum.php');
		$pages = numofpage($count,$page,ceil($count/$perpage),"$basename&action=argument&step=list&$addpage");
		}
	}elseif($step == 'delete'){
		$selids = '';
		InitGP(array('selid'),'P',1);
		if (is_array($selid)) {
			foreach ($selid as $value) {
				if (is_numeric($value)) {
					$selids .= ($selids ? ',' : '')."'$value'";
				}
			}
		}
		!$selids && adminmsg('selid_illegal');
		$selids = strpos($selids,',')!==false ? "IN ($selids)" : "= $selids";
		$db->update("DELETE FROM pw_argument WHERE tid $selids");
		$db->update("DELETE FROM pw_argument WHERE tpcid $selids");
		adminmsg('operate_success',"$basename&action=argument&");
	}else{
		@include_once(D_P.'data/bbscache/cn_class.php');
		empty($cnclassdb) && $cnclassdb = array();
		foreach($cnclassdb as $key => $value){
			$classoption .= '<option value="'.$key.'">'.$value[cname].'</option>'; 
		}
	}
	require_once PrintHack('admin');
}
function Delcnimg($filename){
	global $attachdir,$db_ftpweb,$ftp;
	if (strpos($filename,'..')!==false) {
		return false;
	}
	if (file_exists("$attachdir/cn_img/$filename")) {
		P_unlink("$attachdir/cn_img/$filename");
	} elseif ($db_ftpweb) {
		$ftp->delete("cn_img/$filename");
	}
}

function updatecache_cnc(){
	global $db;
	$cnclassdb = array();
	$query = $db->query('SELECT cid,cname,cnsum FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$cnclassdb[$rt['cid']] = array('cname' => $rt['cname'],'cnsum' => $rt['cnsum']);
	}
	writeover(D_P."data/bbscache/cn_class.php","<?php\r\n\$cnclassdb=".pw_var_export($cnclassdb).";\r\n?>");
}
?>